package com.wysql.common.exception;

import com.wysql.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
@Slf4j
@Component
public class GlobalExceptionHandler {
    @ExceptionHandler({CommonException.class})
    public R<String> handleException(CommonException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',权限码校验失败'{}'", requestURI, e.getCommonExceptionType().getMsg());
        e.printStackTrace();
        return R.error(e.getCommonExceptionType().getCode(), e.getCommonExceptionType().getMsg());
    }

    @ExceptionHandler({OptionalException.class})
    public R<String> handleException(OptionalException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        e.printStackTrace();
        log.error("请求地址'{}',自定义错误'{}'", requestURI, e.getMsg());
        return R.error(e.getCode(), e.getMsg());
    }

    @ExceptionHandler({BindException.class})
    public R<String> handleException(BindException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',自定义错误'{}'", requestURI, e.getMessage());
        e.printStackTrace();
        return R.error(CommonExceptionType.PARAMETER_ERROR.getCode(), e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    @ExceptionHandler({Exception.class})
    public R<String> handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',自定义错误'{}'", requestURI, e.getMessage());
        e.printStackTrace();
        return R.error(CommonExceptionType.SYS_ERROR.getCode(), "错误");
    }
}
